//
//  LogOnViewController.m
//  Bracelet
//
//  Created by jing zhao on 2/16/15.
//  Copyright (c) 2015 jing zhao. All rights reserved.
//

#import "LogOnViewController.h"
#import "APILogOn.h"
#import "AppDelegate.h"
#import "AlertView.h"


@interface LogOnViewController ()<UIPickerViewDataSource,UIPickerViewDelegate,UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UIView *       ui_viewContainer;
@property (weak, nonatomic) IBOutlet UITextField *  ui_textFieldUserName;
@property (weak, nonatomic) IBOutlet UITextField *  ui_textFieldUserCity;
@property (weak, nonatomic) IBOutlet UITextField *  ui_textFieldDepartment;
@property (weak, nonatomic) IBOutlet UIView *       ui_containerPickView;
@property (weak, nonatomic) IBOutlet UIPickerView * ui_PickView;
@property (weak, nonatomic) IBOutlet UIButton *ui_buttonStartNow;
@property (weak, nonatomic) IBOutlet UIScrollView *ui_scrollview;

@property (strong, nonatomic)NSArray *              arrayTextField;
@property (strong, nonatomic)APILogOnCity *         citysInfo;
@property (strong, nonatomic)APILogOnDeparment *    departmentsInfo;
@property (unsafe_unretained, nonatomic)NSInteger   selectedButtonTag;

//@property (weak, nonatomic) IBOutlet NSLayoutConstraint *   constraint_ViewTop;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *constraintHeight;

@end

@implementation LogOnViewController

- (void)viewDidLoad {
    [super viewDidLoad];
  self.ui_textFieldDepartment.layer.borderColor = [UIColor colorWithRed:103/255.f green:103/255.f blue:103/255.f alpha:1.0f].CGColor;
  self.ui_textFieldUserName.layer.borderColor = [UIColor colorWithRed:103/255.f green:103/255.f blue:103/255.f alpha:1.0f].CGColor;
  self.ui_textFieldUserCity.layer.borderColor = [UIColor colorWithRed:103/255.f green:103/255.f blue:103/255.f alpha:1.0f].CGColor;
  self.ui_textFieldDepartment.layer.borderWidth = 1.0;
  self.ui_textFieldUserName.layer.borderWidth = 1.0;
  self.ui_textFieldUserCity.layer.borderWidth = 1.0;
  
    self.ui_textFieldUserName.text = [[NSUserDefaults standardUserDefaults]objectForKey:@"userName"];
//  
//    if (self.ui_scrollview.frame.size.height>518.0f) {
//        self.constraintHeight.constant = self.ui_scrollview.frame.size.height;
//    }
    self.ui_scrollview.contentSize = CGSizeMake(self.ui_scrollview.frame.size.width, 518.0f);
       //self.ui_textFieldUserName.text = @"user001";
  
    [APILogOn getTheCitywithSuccess:^(APILogOnCity *logOncity) {
        self.citysInfo = logOncity;
    } failure:^(NSError *error) {
        [self showNoInternet];
    }];
    
    [APILogOn getTheDepartmentwithSuccess:^(APILogOnDeparment *logOnDepartment) {
        self.departmentsInfo = logOnDepartment;
    } failure:^(NSError *error) {
        [self showNoInternet];
    }];
    _ui_buttonStartNow.enabled = NO;
    _ui_buttonStartNow.backgroundColor = [UIColor colorWithRed:185/255.0 green:128/255.0 blue:135/255.0 alpha:1.0];

}
- (void)viewDidLayoutSubviews
{

    if (self.ui_scrollview.frame.size.height>518.0f) {
        self.constraintHeight.constant = self.ui_scrollview.frame.size.height;
    }
}

-(void)viewDidAppear:(BOOL)animated
{

    self.arrayTextField =@[_ui_textFieldUserName,_ui_textFieldUserCity,_ui_textFieldDepartment];
    
    self.ui_PickView.delegate = self;
    self.ui_PickView.dataSource = self;
    self.selectedButtonTag = 0;
    self.ui_containerPickView.hidden = YES;
}


- (void)viewWillDisappear:(BOOL)animated
{
    [self viewDidDisappear:animated];
    [self removeALlObserve];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(BOOL)prefersStatusBarHidden{
    //return YES;
    return NO;
}

/*function*/

- (IBAction)startNow:(id)sender {

    BOOL boolRight = true;
    if (boolRight) {
        self.ui_buttonStartNow.userInteractionEnabled = false;
        NSUInteger cityNameInterger = [self.citysInfo.arrayCityEnglishName indexOfObject:self.ui_textFieldUserCity.text ];
        NSString *cityId = [self.citysInfo.arrayCityId objectAtIndex:cityNameInterger];
        NSUInteger departmentInterger = [self.departmentsInfo.arrayDepartmentName indexOfObject:self.ui_textFieldDepartment.text];
        NSString *deparmentId = [self.departmentsInfo.arrayDepartementId objectAtIndex:departmentInterger];
       
       
     [APILogOn  setApiLogOnWithUserName:self.ui_textFieldUserName.text
                          andWithCityId:cityId
                            andBranchId:@""
                        andDepartmentId:deparmentId
                            andMobileId:nil
                                success:^(APILogOn *logOn) {
         UINavigationController *navigationController = (UINavigationController *)self.frostedViewController.contentViewController;
         HomeViewController *secondViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"HomeViewController"];
         navigationController.viewControllers = @[secondViewController];
     } failure:^(NSError *error) {
        [self showNoInternet];
         self.ui_buttonStartNow.userInteractionEnabled = true;
     }];
    }
    else{
        /*
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"error" message:stringTemp delegate:nil cancelButtonTitle:@"cancel" otherButtonTitles:nil];
        [alert show];
         */
    }
}

- (IBAction)selectButton:(id)sender {
     [self.ui_textFieldUserName resignFirstResponder];
    UIButton *buttonTemp =(UIButton*)sender;
    self.selectedButtonTag = buttonTemp.tag;
    if ([[self getTheCurrentArray]count] ==0) {
//        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"info" message:@"Loading, please wait.." delegate:nil cancelButtonTitle:@"cancel" otherButtonTitles:nil];
//        [alert show];
    }
     self.ui_containerPickView.hidden  = NO;
    [self.ui_PickView reloadAllComponents];
    [self.ui_PickView selectRow:3 inComponent:0 animated:NO];
}

/*  pickView*/

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
     return  [[self getTheCurrentArray]count];
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    NSArray *arrayTemp = [self getTheCurrentArray];
    NSString *strTemp = [arrayTemp objectAtIndex:row];
    return strTemp;
}

- (IBAction)pickButtonCancel:(id)sender {
    
     self.ui_containerPickView.hidden = YES;
}

- (IBAction)pickButtonSure:(id)sender {
    NSArray *arrayTemp =[self getTheCurrentArray];
    UITextField *textFieldTemp= [self.arrayTextField objectAtIndex:self.selectedButtonTag];
    textFieldTemp.text =[arrayTemp objectAtIndex:[self.ui_PickView selectedRowInComponent:0]];
    if ([self isClickedStartNow] ) {
        _ui_buttonStartNow.backgroundColor = [UIColor colorWithRed:140/225.0 green:10/255.0 blue:65/255.0 alpha:1.0];
        _ui_buttonStartNow.enabled = YES;
    }else{
        
     _ui_buttonStartNow.enabled = NO;
    }
    self.ui_containerPickView.hidden = YES;
}


- (BOOL) isClickedStartNow{
    BOOL boolRight = true;
    NSString *stringTemp = @"UserName can not be blank";
    UITextField *textFieldCity= (UITextField*)[self.arrayTextField objectAtIndex:1];
    UITextField *textFieldDepartment =(UITextField*)[self.arrayTextField objectAtIndex:2];
    
    if ([textFieldCity.text isEqualToString:@"Please select"]||[textFieldCity.text isEqualToString:@""] ) {
        stringTemp = @"Please choose city";
        boolRight = false;
    }
    else if ([textFieldDepartment.text isEqualToString:@"Please select"]||[textFieldDepartment.text isEqualToString:@""])
    {
        stringTemp = @"Please choose department";
        boolRight = false;
    }

    return boolRight;
}

-(NSArray*)getTheCurrentArray
{
    NSArray *array;
    switch (self.selectedButtonTag) {
        case 1:{
            array = self.citysInfo.arrayCityEnglishName;
            break;
        }
        default:{
            array = self.departmentsInfo.arrayDepartmentName;
            break;
        }
    }
    return array;
}


-(void)removeALlObserve
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.ui_textFieldUserName resignFirstResponder];
    return YES;
}

- (IBAction)buttonBack:(id)sender {
    [self.frostedViewController presentMenuViewController];
}

- (IBAction)showMenu
{
    //because now log on page don't need show menu
    //[self.frostedViewController presentMenuViewController];
    [[(AppDelegate *)[[UIApplication sharedApplication] delegate] viewController].navigationController popViewControllerAnimated:YES];
          
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    if ([self.ui_textFieldUserName isFirstResponder]) {
        [self.ui_textFieldUserName resignFirstResponder];
    }
}

- (void)showNoInternet{
    AlertView * alert = [AlertView shareInstance];
    alert = [[[NSBundle mainBundle]loadNibNamed:@"AlertView" owner:self options:nil] lastObject];
    alert.alertTitle.text = @"Oops!";
    alert.alertMessage.text = @"No internet connection. Please check your network. \n \n ";
    alert.frame = [[UIScreen mainScreen] bounds];
    [self.view addSubview:alert];
}
@end
